package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

//开启注解放入spring容器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //    自动注入数据库
    @Autowired
    private DataSource dataSource;
//    进行用户授权

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/index", "/index.html").permitAll()
                .antMatchers("/vip1/*", "/vip1").hasRole("vip1")
                .antMatchers("/vip2/*", "/vip2").hasRole("vip2")
                .antMatchers("/vip3/*", "/vip3").hasRole("vip3");
//        忽略druid
        http.csrf().ignoringAntMatchers("/druid/*");
//        设置其他所有路由都需要认证
        http.authorizeRequests().anyRequest().authenticated();

//        没有权限的访问登录页面
        http.formLogin();
//        开启注销功能
        http.logout().logoutSuccessUrl("/");
    }

//    进行用户角色分配

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        从内存中读取角色
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3").and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2").and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
//        从数据库中读取数据资源
        auth.jdbcAuthentication().dataSource(dataSource)
                .passwordEncoder(new BCryptPasswordEncoder())
                .usersByUsernameQuery("select username,password,enabled from mytest where username=?")
                .authoritiesByUsernameQuery("select username,authority from mytestauth where username=?");

    }
}